<template>
  <div class="prescription-payment-page">
    <van-nav-bar
      title="开单支付"
      left-arrow
      @click-left="goBack"
    >
      <template #right>
        <div class="nav-icons">
          <span class="dot"></span>
          <span class="dot"></span>
          <span class="dot"></span>
          <span class="circle-btn"></span>
        </div>
      </template>
    </van-nav-bar>

    <div class="content" v-if="!loading">
      <!-- 申请项目 -->
      <div class="section">
        <div class="section-title">申请项目</div>
        
        <!-- 药品项目 -->
        <div 
          v-for="item in drugItems" 
          :key="`drug-${item.id}`"
          class="item-card"
        >
          <div class="item-header">
            <span class="item-type drug">药</span>
            <span class="item-name">{{ item.itemName }}</span>
            <span class="item-price">¥{{ item.amount.toFixed(2) }}</span>
          </div>
          <div class="item-details">
            <span>数量：{{ item.quantity }}{{ getItemUnit(item.itemType) }}</span>
            <span class="item-category">{{ getItemCategory(item.itemName) }}</span>
          </div>
        </div>

        <!-- 检查项目 -->
        <div 
          v-for="item in checkupItems" 
          :key="`checkup-${item.id}`"
          class="item-card"
        >
          <div class="item-header">
            <span class="item-type checkup">查</span>
            <span class="item-name">{{ item.itemName }}</span>
            <span class="item-price">¥{{ item.amount.toFixed(2) }}</span>
          </div>
          <div class="item-details">
            <span>数量：{{ item.quantity }}次</span>
          </div>
        </div>

        <!-- 检验项目 -->
        <div 
          v-for="item in testItems" 
          :key="`test-${item.id}`"
          class="item-card"
        >
          <div class="item-header">
            <span class="item-type test">验</span>
            <span class="item-name">{{ item.itemName }}</span>
            <span class="item-price">¥{{ item.amount.toFixed(2) }}</span>
          </div>
          <div class="item-details">
            <span>数量：{{ item.quantity }}次</span>
          </div>
        </div>
      </div>

      <!-- 支付方式 -->
      <div class="section">
        <div class="section-title">支付方式</div>
        <div class="payment-method">
          <van-radio-group v-model="selectedPaymentMethod">
            <van-radio name="balance" icon-size="20px">
              自费支付
            </van-radio>
            <van-radio name="medical" icon-size="20px">
              医保支付
            </van-radio>
          </van-radio-group>
        </div>
      </div>
    </div>

    <!-- 底部支付栏 -->
    <div class="payment-footer">
      <div class="total-section">
        <div class="total-label">合计：</div>
        <div class="total-amount">¥{{ totalAmount.toFixed(2) }}</div>
      </div>
      <van-button 
        type="primary" 
        class="pay-button"
        :loading="paymentLoading"
        @click="handlePayment"
      >
        立即支付
      </van-button>
    </div>

    <!-- 支付成功弹窗 -->
    <van-popup v-model:show="showSuccessPopup" class="success-popup">
      <div class="success-content">
        <van-icon name="checked" color="#07c160" size="60px" />
        <div class="success-title">已支付</div>
        <div class="success-message">
          您已缴费成功，如需打印发票请联系医院工作人员，目前药品暂不支持快递配送，请到院门诊药房6号便民窗口取药
        </div>
        <div class="hospital-info">
          <div class="info-row">
            <span class="info-label">申请医院</span>
            <span class="info-value">{{ prescription.hospitalName }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">就诊患者</span>
            <span class="info-value">{{ prescription.userName }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">登记卡号</span>
            <span class="info-value">{{ prescription.userId }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">开单金额</span>
            <span class="info-value">¥{{ prescription.totalAmount.toFixed(2) }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">申请时间</span>
            <span class="info-value">{{ formatDateTime(prescription.applicationTime) }}</span>
          </div>
        </div>
        <div class="success-actions">
          <van-button 
            type="primary" 
            block 
            round 
            @click="goBackToRecords"
          >
            返回开单记录
          </van-button>
        </div>
      </div>
    </van-popup>

    <!-- 加载状态 -->
    <van-loading v-if="loading" class="loading-spinner" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { axiosrnewmedical } from '@/http/axiosRead';
import { showNotify } from 'vant';
import { PaymentHelper, PaymentMethod, ItemType, type PaymentItem } from '@/utils/paymentHelper';

// 接口定义
interface PrescriptionDetail {
  id: number;
  applicationId: number;
  itemType: number;
  itemTypeName: string;
  itemId: number;
  itemName: string;
  quantity: number;
  unitPrice: number;
  amount: number;
}

interface Prescription {
  id: number;
  hospitalId: number;
  hospitalName: string;
  userId: number;
  userName: string;
  applicationTime: string;
  status: number;
  statusName: string;
  totalAmount: number;
  applyReason: string;
  auditorId: number;
  auditorName: string;
  auditTime: string;
  rejectReason: string;
  paymentTime: string;
  cancelTime: string;
  details: PrescriptionDetail[];
}

const router = useRouter();

// 响应式数据
const loading = ref(false);
const paymentLoading = ref(false);
const prescription = ref<Prescription>({} as Prescription);
const selectedPaymentMethod = ref('balance');
const showSuccessPopup = ref(false);

// 计算属性
const drugItems = computed(() => 
  prescription.value.details?.filter(item => item.itemType === 1) || []
);

const checkupItems = computed(() => 
  prescription.value.details?.filter(item => item.itemType === 2) || []
);

const testItems = computed(() => 
  prescription.value.details?.filter(item => item.itemType === 3) || []
);

const totalAmount = computed(() => {
  // 如果有prescription的totalAmount就用它，否则从details重新计算
  if (prescription.value.totalAmount && prescription.value.totalAmount > 0) {
    return prescription.value.totalAmount;
  }
  // 从details重新计算总金额
  return prescription.value.details?.reduce((sum, item) => sum + item.amount, 0) || 0;
});



// 购物车项目接口
interface CartItem {
  drug?: {
    id: number;
    drugName: string;
    price: number;
  };
  checkupItem?: {
    id: number;
    itemName: string;
    price: number;
  };
  testItem?: {
    id: number;
    itemName: string;
    price: number;
  };
  quantity: number;
}



// 从购物车数据构建处方详情
const buildPrescriptionFromCart = async () => {
  // 直接使用购物车数据，不调用API接口
  const storedItems = localStorage.getItem('selectedItems');
  console.log('从localStorage获取的购物车数据:', storedItems);
  
  if (!storedItems) {
    showNotify({ type: 'warning', message: '没有找到购物车数据' });
    router.back();
    return;
  }

  try {
    const cartItems: CartItem[] = JSON.parse(storedItems);
    console.log('解析后的购物车数据:', cartItems);
    const details: PrescriptionDetail[] = [];
    let totalAmount = 0;

    cartItems.forEach((item: CartItem) => {
      if (item.drug) {
        const amount = item.drug.price * (item.quantity || 1);
        details.push({
          id: item.drug.id,
          applicationId: 0,
          itemType: 1,
          itemTypeName: '药品',
          itemId: item.drug.id,
          itemName: item.drug.drugName,
          quantity: item.quantity || 1,
          unitPrice: item.drug.price,
          amount: amount
        });
        totalAmount += amount;
      } else if (item.checkupItem) {
        const amount = item.checkupItem.price;
        details.push({
          id: item.checkupItem.id,
          applicationId: 0,
          itemType: 2,
          itemTypeName: '检查',
          itemId: item.checkupItem.id,
          itemName: item.checkupItem.itemName,
          quantity: 1,
          unitPrice: item.checkupItem.price,
          amount: amount
        });
        totalAmount += amount;
      } else if (item.testItem) {
        const amount = item.testItem.price;
        details.push({
          id: item.testItem.id,
          applicationId: 0,
          itemType: 3,
          itemTypeName: '检验',
          itemId: item.testItem.id,
          itemName: item.testItem.itemName,
          quantity: 1,
          unitPrice: item.testItem.price,
          amount: amount
        });
        totalAmount += amount;
      }
    });

    // 获取患者信息
    let userId = 1; // 默认患者ID
    let userName = '默认患者'; // 默认患者姓名
    
    try {
      // 尝试从API获取患者信息
      const accountId = localStorage.getItem('userId') || '1';
      const response = await axiosrnewmedical.get(`/Patient/GetPatientByAccountId`, {
        params: { accountId: accountId }
      });
      
      if (response.data.code === 200 && response.data.data) {
        const patientData = Array.isArray(response.data.data) 
          ? response.data.data[0] 
          : response.data.data;
        
        userId = patientData.id;
        userName = patientData.name;
      }
    } catch (error) {
      console.log('获取患者信息失败，使用默认值:', error);
    }

    prescription.value = {
      id: 0, // 购物车数据时暂时设为0，支付时需要先创建申请
      hospitalId: 1,
      hospitalName: localStorage.getItem('hospitalName') || '四川省保健院北苑',
      userId: userId,
      userName: userName,
      applicationTime: new Date().toISOString(),
      status: 0,
      statusName: '购物车数据',
      totalAmount: totalAmount,
      applyReason: '',
      auditorId: 0,
      auditorName: '',
      auditTime: '',
      rejectReason: '',
      paymentTime: '',
      cancelTime: '',
      details: details
    };

    console.log('使用购物车数据构建支付页面');
    console.log('计算的总金额:', totalAmount);
    console.log('详情数据:', details);
    console.log('prescription对象:', prescription.value);
  } catch (error) {
    console.error('解析购物车数据失败:', error);
    showNotify({ type: 'danger', message: '购物车数据格式错误' });
    router.back();
  }
};









// 处理支付
const handlePayment = async () => {
  paymentLoading.value = true;
  
  try {
    // 构建支付项目列表
    const paymentItems: PaymentItem[] = [];
    
    // 添加药品项目
    drugItems.value.forEach(item => {
      paymentItems.push({
        itemId: item.itemId,
        itemType: ItemType.DRUG,
        amount: item.amount,
        quantity: item.quantity
      });
    });
    
    // 添加检查项目
    checkupItems.value.forEach(item => {
      paymentItems.push({
        itemId: item.itemId,
        itemType: ItemType.CHECKUP,
        amount: item.amount,
        quantity: item.quantity
      });
    });
    
    // 添加检验项目
    testItems.value.forEach(item => {
      paymentItems.push({
        itemId: item.itemId,
        itemType: ItemType.TEST,
        amount: item.amount,
        quantity: item.quantity
      });
    });
    
    // 构建支付参数
    const paymentParams = {
      patientId: prescription.value.userId,
      items: paymentItems,
      paymentMethod: selectedPaymentMethod.value as PaymentMethod,
      cashierId: Number(localStorage.getItem('userId') || '1')
    };
    
    // 验证支付参数
    const validation = PaymentHelper.validatePaymentParams(paymentParams);
    if (!validation.isValid) {
      showNotify({ type: 'warning', message: validation.message });
      return;
    }
    
    // 执行支付
    const result = await PaymentHelper.executePayment(paymentParams);
    
    // 显示支付结果
    PaymentHelper.showPaymentNotification(result);
    
    if (result.success) {
      // 清空购物车和申请ID
      localStorage.removeItem('selectedItems');
      localStorage.removeItem('currentPrescriptionApplicationId');
      
      // 跳转到详情页面
      router.push({
        path: '/prescription-detail',
        query: {
          id: result.prescriptionApplicationId
        }
      });
    }
    
  } catch (error) {
    console.error('支付处理异常:', error);
    const errorMessage = error instanceof Error ? error.message : '支付处理异常，请稍后再试';
    showNotify({ 
      type: 'danger', 
      message: errorMessage,
      duration: 5000
    });
  } finally {
    paymentLoading.value = false;
  }
};

// 更新申请状态 (暂时注释掉，因为接口404)
// const updatePrescriptionStatus = async () => {
//   try {
//     await axioswnewmedical.put('/Prescription/UpdatePrescriptionStatus', {
//       id: prescription.value.id,
//       status: 3, // 已支付状态
//       paymentTime: new Date().toISOString()
//     });
//   } catch (error) {
//     console.error('更新状态失败:', error);
//   }
// };

// 获取项目单位
const getItemUnit = (itemType: number) => {
  switch (itemType) {
    case 1: return '剂';
    case 2: return '次';
    case 3: return '次';
    default: return '';
  }
};

// 获取项目分类
const getItemCategory = (itemName: string) => {
  if (itemName.includes('处方') || itemName.includes('药')) {
    return '处方5剂';
  }
  return '处方药';
};

// 格式化日期时间
const formatDateTime = (dateString: string) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 返回开单记录页面
const goBackToRecords = () => {
  showSuccessPopup.value = false;
  router.push('/prescription-record');
};

onMounted(() => {
  // 直接使用购物车数据，不调用API接口
  buildPrescriptionFromCart();
});
</script>

<style scoped>
.prescription-payment-page {
  height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.nav-icons {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dot {
  width: 4px;
  height: 4px;
  border-radius: 50%;
  background-color: #666;
}

.circle-btn {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 1px solid #666;
}

.content {
  flex: 1;
  overflow-y: auto;
  padding: 0 16px 100px;
}

.section {
  margin-bottom: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 12px;
  padding: 0 4px;
}

.item-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.item-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.item-type {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  border-radius: 4px;
  color: white;
  font-size: 12px;
  font-weight: 600;
  margin-right: 8px;
  flex-shrink: 0;
}

.item-type.drug {
  background-color: #1890ff;
}

.item-type.checkup {
  background-color: #52c41a;
}

.item-type.test {
  background-color: #fa8c16;
}

.item-name {
  flex: 1;
  font-size: 14px;
  color: #323233;
  margin-right: 8px;
}

.item-price {
  font-size: 16px;
  font-weight: 600;
  color: #ee0a24;
}

.item-details {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #969799;
}

.item-category {
  background-color: #f5f5f5;
  padding: 2px 6px;
  border-radius: 4px;
  color: #666;
}

.payment-method {
  background: white;
  border-radius: 8px;
  padding: 16px;
}

.payment-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 16px;
  border-top: 1px solid #ebedf0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  z-index: 1000;
}

.total-section {
  flex: 1;
  display: flex;
  align-items: center;
}

.total-label {
  font-size: 14px;
  color: #969799;
  margin-right: 8px;
}

.total-amount {
  font-size: 20px;
  font-weight: 600;
  color: #ee0a24;
}

.pay-button {
  width: 120px;
  height: 44px;
  border-radius: 22px;
  font-size: 16px;
  font-weight: 600;
}

.success-popup {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.success-content {
  background: white;
  border-radius: 12px;
  padding: 32px 24px;
  width: 90%;
  max-width: 400px;
  text-align: center;
}

.success-title {
  font-size: 20px;
  font-weight: 600;
  color: #323233;
  margin: 16px 0 12px;
}

.success-message {
  font-size: 14px;
  color: #646566;
  line-height: 1.5;
  margin-bottom: 24px;
}

.hospital-info {
  text-align: left;
  border-top: 1px solid #ebedf0;
  padding-top: 16px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  font-size: 14px;
}

.info-label {
  color: #969799;
}

.info-value {
  color: #323233;
  font-weight: 500;
}

.success-actions {
  margin-top: 24px;
}

.loading-spinner {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style> 